package com.brand.data.service.yqdz;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import com.brand.data.model.RequestParam;
import org.apache.commons.io.FileUtils;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.brand.data.model.MonitorException;
import com.brand.data.service.AbstractBaseService;
import com.brand.data.service.LoginService;
import com.brand.data.util.CookieUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author scl
 * @date 2018年4月11日 下午2:47:03
 * @version 1.0
 * @description 一汽大众
 */
@Service
@Slf4j
public class YqdzLoginService extends AbstractBaseService implements LoginService {
	private static final String BRAND_NAME = "YI_QI_DA_ZHONG";
	private static final String UESRNAME = "S751051R03";
	private static final String PASSWORD = "yJ123456";
	static final String URL = "https://portal.faw-vw.com/tejct/testfaw/vw.htm";
	static final String URL_LOGIN = "https://portal.faw-vw.com/pkmslogin.form";
    static RequestParam params = RequestParam.newParam();

	private RequestParam getParams() throws IOException {
		String account = FileUtils.readFileToString(new File("config.json"), "UTF-8");
		JSONObject accObj = JSON.parseObject(account);
		params.addParam("logonID", "")
                .addParam("login-form-type", "pwd")
                .addParam("username", accObj.getString("username"))
                .addParam("password", accObj.getString("password"));
		return params;
	}

	public Boolean login() {
		long start = System.currentTimeMillis();
		doLogin(0);
		long end = System.currentTimeMillis();
		log.info("一汽大众执行登录耗时：{}", end - start);
		return true;
	}

	private void doLogin(int times) {
		try {
			doLogin();
		} catch (Exception e) {
			CookieUtil.clearCookie(BRAND_NAME);
			if (times >= 3) {
				if (e instanceof MonitorException) {
					throw (MonitorException) e;
				}
				throw new MonitorException("登录失败", e.getMessage());
			}
			doLogin(++times);
		}
	}

	private void doLogin() throws Exception {
		Response response = getConnection(URL_LOGIN, getParams(), RequestHeader.initHeader())
				.method(Method.POST).execute();
		String body = response.body();
		if (!body.contains("Your login was successful")) {
			throw new RuntimeException("登录异常");
		}
		//登录成功后获取JSESSIONID
        Map<String, String> cookies = response.cookies();
        response = getConnection("https://portal.faw-vw.com/Portal_SSO/SSORequest.action")
                .headers(RequestHeader.initHeader()).cookies(cookies).execute();
        cookies.putAll(response.cookies());
       /* response = getConnection("https://portal.faw-vw.com/wpsvw/myportal")
                .headers(RequestHeader.initHeader()).cookies(cookies).execute();
        cookies.putAll(response.cookies());
*/
        cookies.put("username",params.get("username"));
		CookieUtil.saveCookie(BRAND_NAME, cookies);
	}
}
